<template>
  <div class="picture-list">
    <!-- 瀑布流布局 -->
    <div class="masonry-container">
      <div class="masonry-column" v-for="(column, index) in masonryColumns" :key="index">
        <div class="masonry-item" v-for="picture in column" :key="picture.id">
          <a-card hoverable @click="doClickPicture(picture)" class="picture-card">
            <template #cover>
              <img
                style="width: 100%; height: auto; object-fit: cover"
                :alt="picture.name"
                :src="picture.url ?? picture.url"
                loading="lazy"
              />
            </template>
            <a-card-meta :title="truncateTitle(picture.name, 10)">
              <template #description>
                <a-flex wrap="wrap" gap="small">
                  <a-tag color="green" v-if="picture.category">
                    {{ truncateTitle(picture.category, 6) }}
                  </a-tag>
                  <a-tag v-for="tag in picture.tags" :key="tag">
                    {{ truncateTitle(tag, 6) }}
                  </a-tag>
                </a-flex>
              </template>
            </a-card-meta>
            <template v-if="showOp" #actions>
              <search-outlined @click="(e) => doSearch(picture, e)" />
              <share-alt-outlined @click="(e) => doShare(picture, e)" />
              <edit-outlined @click="(e) => doEdit(picture, e)" />
              <delete-outlined @click="(e) => doDelete(picture, e)" />
            </template>
          </a-card>
        </div>
      </div>
    </div>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import {
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  ShareAltOutlined,
} from '@ant-design/icons-vue'
import { deletePictureUsingPost } from '@/api/pictureController'
import { message } from 'ant-design-vue'
import ShareModal from '@/components/ShareModal.vue'
import { ref, computed, onMounted, onUnmounted } from 'vue'

interface Props {
  dataList?: API.PictureVO[]
  loading?: boolean
  showOp?: boolean
  onReload?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  loading: false,
  showOp: false,
})

// 新增标题截断方法
const truncateTitle = (str: string, maxLength: number) => {
  if (!str) return '未命名'
  return str.length > maxLength ? str.substring(0, maxLength) + '...' : str
}

// 瀑布流列数（根据屏幕宽度动态调整）
const columnCount = ref(5) // 默认6列

// 计算瀑布流列
const masonryColumns = computed(() => {
  const columns = Array.from({ length: columnCount.value }, () => [])
  if (!props.dataList) return columns

  // 简单分配图片到各列
  props.dataList.forEach((picture, index) => {
    columns[index % columnCount.value].push(picture)
  })

  return columns
})

// 响应式调整列数
const updateColumnCount = () => {
  const width = window.innerWidth
  if (width < 640) {
    columnCount.value = 1
  } else if (width < 768) {
    columnCount.value = 2
  } else if (width < 1024) {
    columnCount.value = 3
  } else if (width < 1280) {
    columnCount.value = 4
  } else {
    columnCount.value = 5 // 大屏幕6列
  }
}

// 初始化时和窗口大小变化时更新列数
onMounted(() => {
  updateColumnCount()
  window.addEventListener('resize', updateColumnCount)
})

onUnmounted(() => {
  window.removeEventListener('resize', updateColumnCount)
})

// 跳转至图片详情
const router = useRouter()
const doClickPicture = (picture) => {
  router.push({
    path: `/picture/${picture.id}`,
  })
}

// 搜索
const doSearch = (picture, e) => {
  e.stopPropagation()
  window.open(`/search_picture?pictureId=${picture.id}`)
}

// 编辑
const doEdit = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  router.push({
    path: '/add_picture',
    query: {
      id: picture.id,
      spaceId: picture.spaceId,
    },
  })
}

// 删除
const doDelete = async (picture, e) => {
  e.stopPropagation()
  const id = picture.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    props?.onReload?.()
  } else {
    message.error('删除失败')
  }
}

// 分享弹窗引用
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()

// 分享
const doShare = (picture: API.PictureVO, e: Event) => {
  e.stopPropagation()
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}
</script>

<style scoped>
.picture-list {
  padding: 0 8px;
}

.masonry-container {
  display: flex;
  gap: 16px; /* 更小的间距 */
  margin: 0 auto;
  max-width: 1800px; /* 更大的最大宽度 */
}

.masonry-column {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 16px; /* 更小的行间距 */
}

.masonry-item {
  break-inside: avoid;
  margin-bottom: 0;
}

.picture-card {
  transition: all 0.3s ease;
  margin-bottom: 0;
  width: 100%;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #f0f0f0;
}

.picture-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.picture-card :deep(.ant-card-body) {
  padding: 12px;
}

.picture-card :deep(.ant-card-meta-title) {
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.picture-card :deep(.ant-tag) {
  font-size: 11px;
  padding: 0 6px;
  margin-bottom: 4px;
}

/* 响应式调整 */
@media (max-width: 1599px) {
  .masonry-container {
    max-width: 1400px;
  }
}

@media (max-width: 1279px) {
  .masonry-container {
    max-width: 1200px;
  }
}

@media (max-width: 1023px) {
  .masonry-container {
    max-width: 900px;
  }
}

@media (max-width: 767px) {
  .masonry-container {
    max-width: 600px;
  }

  .picture-card :deep(.ant-card-meta-title) {
    font-size: 14px;
  }
}

@media (max-width: 639px) {
  .masonry-container {
    max-width: 100%;
    padding: 0 4px;
  }

  .picture-card {
    border-radius: 4px;
  }

  .picture-card :deep(.ant-card-body) {
    padding: 8px;
  }
}
</style>
